<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>个人资料</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; font-family: "Microsoft YaHei", sans-serif; }
        body { background-color: #f5f7fa; }
        /* 顶部导航栏 */
        .nav { width: 100%; height: 60px; background-color: #2c3e50; display: flex; align-items: center; padding: 0 50px; }
        .nav-logo { color: white; font-size: 22px; font-weight: bold; text-decoration: none; margin-right: 50px; }
        .nav-menu { display: flex; gap: 30px; }
        .nav-menu a { color: #ecf0f1; text-decoration: none; font-size: 16px; }
        .nav-menu a:hover { color: #3498db; }
        .nav-user { margin-left: auto; color: white; display: flex; align-items: center; gap: 15px; }
        .nav-user a { color: white; text-decoration: none; }
        
        .container { width: 600px; margin: 50px auto; }
        .form-group { margin: 15px 0; }
        label { display: inline-block; width: 80px; }
        input { padding: 8px; width: 400px; }
        .btn { padding: 10px 20px; background: #007bff; color: white; border: none; cursor: pointer; }
        .error { color: red; }
        .success { color: green; }
    </style>
</head>
<body>
<!-- 顶部导航栏 -->
<nav class="nav">
    <a href="/echo-network/article-list.html" class="nav-logo">回声网络</a >
    <div class="nav-menu">
        <a href="/echo-network/article-list">首页</a >
        <a href="/echo-network/article-publish.html">发布文章</a >
        <a href="/echo-network/article-show">我的文章</a >
        <!-- 管理员专用的分类文章按钮 -->
        <a href="/echo-network/admin/categoryList.html" th:if="${session.loginUser != null && session.loginUser.role == 1}">分类文章</a >
        <a href="/echo-network/login.html">重新登录</a>
    </div>
    <div class="nav-user" th:if="${session.loginUser != null}">
        <span th:text="${session.loginUser.nickname}"></span>
        <a href="#" onclick="confirmLogout(event)">注销</a >
    </div>
    <div class="nav-user" th:if="${session.loginUser == null}">
        <a href="/login.html">登录</a >
        <a href="/register.html">注册</a >
    </div>
</nav>
<div class="container">
    <h1>个人资料修改</h1>
    <!-- 提示信息 -->
    <p class="error" th:text="${errorMsg}"></p >
    <p class="success" th:text="${successMsg}"></p >

    <!-- 资料修改表单 -->
    <form action="/echo-network/profile/update" method="post" enctype="multipart/form-data">
        <div class="form-group">
            <label>用户名：</label>
            <input type="text" th:value="${user.username}" disabled> <!-- 用户名不可修改 -->
        </div>
        <div class="form-group">
            <label>邮箱：</label>
            <input type="email" name="email" th:value="${user.email}">
        </div>
        <div class="form-group">
            <label>昵称：</label>
            <input type="text" name="nickname" th:value="${user.nickname}">
        </div>
        <div class="form-group">
            <label>头像：</label>
            <input type="file" name="avatarFile" accept="image/*" style="margin-top: 10px;">
            <p style="margin-top: 10px; font-size: 14px; color: #666;">当前头像：<span th:if="${user.avatar != null && user.avatar != ''}" th:text="${user.avatar}">无</span><span th:unless="${user.avatar != null && user.avatar != ''}">默认头像</span></p>
            <input type="hidden" name="avatar" th:value="${user.avatar}">
        </div>
        <div class="form-group">
            <label></label>
            <button type="submit" class="btn">保存修改</button>
            <a href="/echo-network/profile-show" style="margin-left: 20px;">返回资料展示</a >
            <a href="/echo-network/reset-password" style="margin-left: 20px;">修改密码</a >
        </div>
    </form>
</div>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 文件上传预览功能
            const avatarFileInput = document.querySelector('input[name="avatarFile"]');
            const form = document.querySelector('form');
            
            // 监听文件选择变化
            avatarFileInput.addEventListener('change', function(e) {
                const file = e.target.files[0];
                if (file) {
                    // 检查文件类型
                    if (!file.type.startsWith('image/')) {
                        alert('请选择有效的图片文件！');
                        avatarFileInput.value = '';
                        return;
                    }
                    
                    // 检查文件大小（限制2MB）
                    if (file.size > 2 * 1024 * 1024) {
                        alert('图片文件大小不能超过2MB！');
                        avatarFileInput.value = '';
                        return;
                    }
                }
            });
            
            // 页面加载时获取原始值
            const emailInput = document.querySelector('input[name="email"]');
            const nicknameInput = document.querySelector('input[name="nickname"]');
            const originalEmail = emailInput.value.trim();
            const originalNickname = nicknameInput.value.trim();
            
            // 表单提交处理
            form.addEventListener('submit', function(e) {
                const avatarFile = avatarFileInput.files[0];
                
                // 获取当前输入的值
                const currentEmail = emailInput.value.trim();
                const currentNickname = nicknameInput.value.trim();
                const avatarChanged = !!avatarFile;
                
                // 检查是否所有字段都没有变化
                // 改进：只有当用户实际修改了邮箱且不为空时才视为修改
                const emailChanged = currentEmail !== originalEmail && currentEmail !== '';
                // 改进：只有当用户实际修改了昵称且不为空时才视为修改
                const nicknameChanged = currentNickname !== originalNickname && currentNickname !== '';
                
                // 调试信息 - 可以帮助排查问题
                console.log('原始邮箱:', originalEmail);
                console.log('当前邮箱:', currentEmail);
                console.log('邮箱是否修改:', emailChanged);
                console.log('原始昵称:', originalNickname);
                console.log('当前昵称:', currentNickname);
                console.log('昵称是否修改:', nicknameChanged);
                console.log('是否上传新头像:', avatarChanged);
                
                // 只有在不修改昵称和邮箱且不上传头像文件时才提示
                if (!emailChanged && !nicknameChanged && !avatarChanged) {
                    alert('请至少修改邮箱、昵称或上传头像文件！');
                    e.preventDefault();
                    return;
                }
                
                // 如果有选择文件，则上传文件获取URL
                if (avatarFile) {
                    e.preventDefault(); // 阻止表单默认提交
                    
                    // 创建FormData对象
                    const formData = new FormData();
                    formData.append('file', avatarFile);
                    
                    // 显示上传中提示
                    const submitButton = document.querySelector('button[type="submit"]');
                    const originalText = submitButton.textContent;
                    submitButton.disabled = true;
                    submitButton.textContent = '上传中...';
                    
                    // 发送文件上传请求
                    const xhr = new XMLHttpRequest();
                    xhr.open('POST', '/echo-network/upload', true);
                    
                    xhr.onload = function() {
                        if (xhr.status === 200) {
                            try {
                                const response = JSON.parse(xhr.responseText);
                                if (response.success) {
                                    // 设置头像URL
                                    document.querySelector('input[name="avatar"]').value = response.fileUrl;
                                    // 提交表单
                                    form.submit();
                                } else {
                                    alert('文件上传失败：' + response.message);
                                    submitButton.disabled = false;
                                    submitButton.textContent = originalText;
                                }
                            } catch (e) {
                                alert('文件上传响应解析失败！');
                                submitButton.disabled = false;
                                submitButton.textContent = originalText;
                            }
                        } else {
                            alert('文件上传请求失败！');
                            submitButton.disabled = false;
                            submitButton.textContent = originalText;
                        }
                    };
                    
                    xhr.onerror = function() {
                        alert('网络错误，请稍后重试！');
                        submitButton.disabled = false;
                        submitButton.textContent = originalText;
                    };
                    
                    xhr.send(formData);
                }
                // 如果没有选择文件，则正常提交表单
            });
            
            // 注销功能
            const logoutLink = document.querySelector('a[onclick="confirmLogout(event)"]');
            if (logoutLink) {
                logoutLink.addEventListener('click', function(event) {
                    event.preventDefault();
                    
                    if (confirm('确定要注销当前账号吗？')) {
                        // 不再使用localStorage记录状态，直接提交表单到LogoutServlet
                        const logoutForm = document.createElement('form');
                        logoutForm.method = 'POST';
                        logoutForm.action = '/echo-network/logout';
                        logoutForm.style.display = 'none';
                        document.body.appendChild(logoutForm);
                        logoutForm.submit();
                    }
                });
            }
            
            // 页面加载时检查URL中的logout参数（由LogoutServlet设置）
            const urlParams = new URLSearchParams(window.location.search);
            const logoutStatus = urlParams.get('logout');
            
            // 如果URL中有logout参数，显示相应的提示
            if (logoutStatus === 'success') {
                alert('注销成功！');
            } else if (logoutStatus === 'fail') {
                alert('注销失败，请重试！');
            }
        });
    </script>
</body>
</html>